package com.epam.DAO.JPA;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.epam.DAO.RequestDAO;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;

public class RequestDAOJPA extends GenericDAOJPA<Request> implements RequestDAO {
	
	public RequestDAOJPA() {
		super(Request.class);
	}

	@Override
	public List<Request> getRequests(Status... status) {
		EntityManager em = getEntityManager();
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r WHERE r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.getResultList();
		em.close();
		return list;
	}

	@Override
	public List<Request> getUserRequests(Client client, Status... status) {
		EntityManager em = getEntityManager();
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r "
						+ "WHERE r.client = :client AND r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.getResultList();
		em.close();
		return list;
	}

}
